package org.changchen.fgt.config;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.changchen.fgt.dto.ApiInfo;
import org.changchen.fgt.utils.UrlUtil;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class SourceApiConfig {
	
	
	public static final String CONFIG_FILE = "config.yml";
	
	
	public static final String DATA_TYPE_JSON = "json";
	
	
	public static final String DATA_TYPE_XML = "xml";
	
	
	public static Map<String,ApiInfo> SRC_CONFIG = new HashMap<>();
	
	
		
	/**   
	 * @Title:      getParentDir   
	 * @Description:获取 Jar 所在目录   
	 * @param:      @return      
	 * @return:     String      
	 * @throws   
	 */
	public String getParentDir() {
		// 获取 jar 所在目录
		ApplicationHome home = new ApplicationHome(this.getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().toString();
	}
	
	
	/**   
	 * @Title:      parseConfig   
	 * @Description:解析 yaml 文件配置   
	 * @param:      @param fileName
	 * @param:      @return      
	 * @return:     Map<String,Object>      
	 * @throws IOException 
	 * @throws   
	 */
	public Map<String, ApiInfo> parseConfig(String fileName) throws IOException{
		
		YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean();
		
		// 外部配置文件
		String yamlFile = this.getParentDir() + File.separator + fileName;
		File extFile = new File(yamlFile);
		if(!extFile.exists()) {
			// 内置配置文件
//			yamlFile = this.getClass().getClassLoader().getResource(fileName).getPath();
//			yamlFile = yamlFile.substring(1, yamlFile.length());
			
			ClassPathResource resource = new ClassPathResource(fileName);
			// 加载 Yaml 文件
			yamlMapFactoryBean.setResources(resource);
		} else {
			yamlMapFactoryBean.setResources(new PathResource(yamlFile));
		}
		
		// 通过 getObject() 方法获取 Map 对象	
		Map<String,Object> srcMap = yamlMapFactoryBean.getObject();
		Map<String,ApiInfo> rsMap = new HashMap<>();
		
		srcMap.entrySet().parallelStream().forEach(item -> {
			
			ApiInfo apiInfo = JSON.parseObject(JSON.toJSONString(item.getValue()), ApiInfo.class);
			apiInfo.setCode(item.getKey());
			
			// 检测资源链接是否能够访问
			if(UrlUtil.testUrlByWebClient(apiInfo.getUrl())) {
				rsMap.put(item.getKey(), apiInfo);
			} else {
				log.error("[{}]({})暂无法访问！", apiInfo.getName(), apiInfo.getUrl());
			}				
		});
		
		return rsMap;
	} 

	
	@PostConstruct
	public void loadConfig() {
		try {
			SRC_CONFIG = this.parseConfig(CONFIG_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
